package cn.com.flat.utils;

import org.apache.commons.io.Charsets;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;
import java.util.jar.JarFile;

/**
 * 标题: 包名工具类
 * <p>
 * 描述: 包名工具类
 * <p>
 * 版权：Copyright (c) 2016
 * <p>
 *
 * @author 张顺
 * @version 1.0
 * @created 2016/11/17/23:22
 */
public class PackageUtil {

    private static Logger logger = LoggerFactory.getLogger(PackageUtil.class);

    private static final String DEFAULT_RESOURCE_PATTERN = "**/*.class";

    /**
     * 扩展转换包名 例:cn.com.flat.modules.*.model转换cn.com.flat.modules.user.model
     * @param aliasesPackageName 包名
     * @return
     */
    public static Set<String> deCodePackageName(String aliasesPackageName){
        Set<String> set = new HashSet<String>();
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(resolver);
        aliasesPackageName = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX+
                ClassUtils.convertClassNameToResourcePath(aliasesPackageName)+"/"+DEFAULT_RESOURCE_PATTERN;

        try {
            Resource[] resources = resolver.getResources(aliasesPackageName);
            if (!StringUtils.isEmpty(resources) && resources.length > 0){
                MetadataReader metadataReader = null;
                for (Resource resource : resources){
                    if (resource.isReadable()){
                        metadataReader = metadataReaderFactory.getMetadataReader(resource);
                        try {
                            set.add(Class.forName(metadataReader.getClassMetadata().getClassName()).getPackage().getName());
                        } catch (ClassNotFoundException e) {
                            e.printStackTrace();
                            return null;
                        }
                    }
                }
            }
        } catch (IOException e) {
            logger.error("获取资源失败",e.getMessage());
            throw new RuntimeException(e.getMessage());
        }
        return set;
    }
}
